<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\TrainingSession;
use App\Models\AiCharacter;
use App\Models\TrainingScenario;
use App\Models\ConversationMessage;
use App\Services\OpenAIService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class TrainingSessionController extends Controller
{
    private $openAIService;

    public function __construct(OpenAIService $openAIService)
    {
        $this->openAIService = $openAIService;
    }

    /**
     * 创建训练会话
     */
    public function create(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'character_id' => 'required|exists:ai_characters,id',
            'scenario_id' => 'required|exists:training_scenarios,id'
        ]);

        if ($validator->fails()) {
            return $this->error('输入数据验证失败', 422, $validator->errors());
        }

        try {
            $character = AiCharacter::findOrFail($request->character_id);
            $scenario = TrainingScenario::findOrFail($request->scenario_id);

            $session = TrainingSession::create([
                'user_id' => $request->user()->id,
                'character_id' => $character->id,
                'scenario_id' => $scenario->id,
                'session_uuid' => (string) Str::uuid(),
                'initial_difficulty' => $character->difficulty_level,
                'status' => 'active'
            ]);

            // 生成AI的开场白
            $openingMessage = $this->generateOpeningMessage($character, $scenario);
            
            ConversationMessage::create([
                'session_id' => $session->id,
                'sender_type' => 'ai',
                'message' => $openingMessage,
                'emotion_score' => 50 // 初始中性情绪
            ]);

            return $this->success([
                'session' => [
                    'id' => $session->id,
                    'session_uuid' => $session->session_uuid,
                    'character' => [
                        'id' => $character->id,
                        'name' => $character->name,
                        'personality_type' => $character->personality_type,
                        'avatar_url' => $character->avatar_url,
                        'difficulty_level' => $character->difficulty_level
                    ],
                    'scenario' => [
                        'id' => $scenario->id,
                        'name' => $scenario->name,
                        'description' => $scenario->description,
                        'objective' => $scenario->objective
                    ],
                    'status' => $session->status,
                    'started_at' => $session->started_at
                ],
                'opening_message' => $openingMessage
            ], '训练会话创建成功');

        } catch (\Exception $e) {
            return $this->error('创建训练会话失败', 500);
        }
    }

    /**
     * 获取训练会话详情
     */
    public function show(TrainingSession $session, Request $request)
    {
        // 检查会话是否属于当前用户
        if ($session->user_id !== $request->user()->id) {
            return $this->error('无权访问此训练会话', 403);
        }

        $session->load(['character', 'scenario', 'messages']);

        return $this->success([
            'session' => [
                'id' => $session->id,
                'session_uuid' => $session->session_uuid,
                'status' => $session->status,
                'initial_difficulty' => $session->initial_difficulty,
                'final_difficulty' => $session->final_difficulty,
                'final_emotion_score' => $session->final_emotion_score,
                'success_achieved' => $session->success_achieved,
                'started_at' => $session->started_at,
                'completed_at' => $session->completed_at,
                'character' => [
                    'id' => $session->character->id,
                    'name' => $session->character->name,
                    'personality_type' => $session->character->personality_type,
                    'avatar_url' => $session->character->avatar_url
                ],
                'scenario' => [
                    'id' => $session->scenario->id,
                    'name' => $session->scenario->name,
                    'description' => $session->scenario->description,
                    'objective' => $session->scenario->objective
                ],
                'messages' => $session->messages->map(function ($message) {
                    return [
                        'id' => $message->id,
                        'sender_type' => $message->sender_type,
                        'message' => $message->message,
                        'emotion_score' => $message->emotion_score,
                        'response_time_ms' => $message->response_time_ms,
                        'is_highlighted' => $message->is_highlighted,
                        'highlight_type' => $message->highlight_type,
                        'created_at' => $message->created_at
                    ];
                })
            ]
        ]);
    }

    /**
     * 发送消息
     */
    public function sendMessage(TrainingSession $session, Request $request)
    {
        // 检查会话是否属于当前用户
        if ($session->user_id !== $request->user()->id) {
            return $this->error('无权访问此训练会话', 403);
        }

        // 检查会话是否还在进行中
        if (!$session->isActive()) {
            return $this->error('训练会话已结束', 400);
        }

        $validator = Validator::make($request->all(), [
            'message' => 'required|string|max:1000'
        ]);

        if ($validator->fails()) {
            return $this->error('消息内容不能为空', 422, $validator->errors());
        }

        try {
            $startTime = microtime(true);

            // 保存用户消息
            $userMessage = ConversationMessage::create([
                'session_id' => $session->id,
                'sender_type' => 'user',
                'message' => $request->message,
                'response_time_ms' => null
            ]);

            // 分析用户消息情感
            $sentiment = $this->openAIService->analyzeSentiment($request->message);
            $userMessage->update(['emotion_score' => $sentiment['score']]);

            // 调整AI难度
            $currentDifficulty = $this->adjustDifficulty($session, $sentiment);

            // 生成AI回复
            $conversationHistory = $this->getConversationHistory($session);
            $aiResponse = $this->openAIService->generateCharacterResponse(
                $session->character->system_prompt,
                $session->scenario->scenario_prompt,
                $conversationHistory,
                $currentDifficulty
            );

            // 保存AI回复
            $aiMessage = ConversationMessage::create([
                'session_id' => $session->id,
                'sender_type' => 'ai',
                'message' => $aiResponse['message'],
                'emotion_score' => $this->calculateAIEmotion($sentiment['score'], $currentDifficulty),
                'response_time_ms' => round((microtime(true) - $startTime) * 1000)
            ]);

            // 检查会话是否应该结束
            $this->checkSessionCompletion($session);

            return $this->success([
                'user_message' => [
                    'id' => $userMessage->id,
                    'message' => $userMessage->message,
                    'emotion_score' => $userMessage->emotion_score,
                    'created_at' => $userMessage->created_at
                ],
                'ai_message' => [
                    'id' => $aiMessage->id,
                    'message' => $aiMessage->message,
                    'emotion_score' => $aiMessage->emotion_score,
                    'response_time_ms' => $aiMessage->response_time_ms,
                    'created_at' => $aiMessage->created_at
                ],
                'session_status' => $session->fresh()->status,
                'current_difficulty' => $currentDifficulty
            ], '消息发送成功');

        } catch (\Exception $e) {
            return $this->error('消息发送失败', 500);
        }
    }

    /**
     * 完成训练会话
     */
    public function complete(TrainingSession $session, Request $request)
    {
        // 检查会话是否属于当前用户
        if ($session->user_id !== $request->user()->id) {
            return $this->error('无权访问此训练会话', 403);
        }

        if (!$session->isActive()) {
            return $this->error('训练会话已结束', 400);
        }

        try {
            // 计算最终情绪分数
            $finalEmotionScore = $this->calculateFinalEmotionScore($session);
            $successAchieved = $finalEmotionScore >= 70;

            $session->update([
                'status' => $successAchieved ? 'completed' : 'failed',
                'completed_at' => now(),
                'final_emotion_score' => $finalEmotionScore,
                'success_achieved' => $successAchieved
            ]);

            // 更新用户统计
            $user = $request->user();
            $statistics = $user->statistics;
            if ($statistics) {
                $statistics->incrementTrainingSession($successAchieved);
            }

            return $this->success([
                'session' => [
                    'id' => $session->id,
                    'status' => $session->status,
                    'final_emotion_score' => $session->final_emotion_score,
                    'success_achieved' => $session->success_achieved,
                    'completed_at' => $session->completed_at
                ],
                'result' => [
                    'success' => $successAchieved,
                    'score' => $finalEmotionScore,
                    'message' => $successAchieved ? '恭喜！训练成功完成！' : '继续努力，下次会更好！'
                ]
            ], '训练会话已完成');

        } catch (\Exception $e) {
            return $this->error('完成训练会话失败', 500);
        }
    }

    /**
     * 放弃训练会话
     */
    public function abandon(TrainingSession $session, Request $request)
    {
        // 检查会话是否属于当前用户
        if ($session->user_id !== $request->user()->id) {
            return $this->error('无权访问此训练会话', 403);
        }

        if (!$session->isActive()) {
            return $this->error('训练会话已结束', 400);
        }

        $session->update([
            'status' => 'abandoned',
            'completed_at' => now()
        ]);

        return $this->success(null, '训练会话已放弃');
    }

    /**
     * 生成开场白
     */
    private function generateOpeningMessage($character, $scenario)
    {
        $openingPrompts = [
            '高冷学霸' => '嗯？有什么事吗？',
            '活泼话痨' => '嗨！你好呀！今天天气真不错呢！',
            '杠精同事' => '又是你啊，有什么事？',
            '温柔体贴' => '你好，很高兴见到你。',
            '幽默风趣' => '哟，这不是...等等，我们认识吗？哈哈！'
        ];

        return $openingPrompts[$character->personality_type] ?? '你好！';
    }

    /**
     * 调整AI难度
     */
    private function adjustDifficulty($session, $sentiment)
    {
        $currentDifficulty = $session->final_difficulty ?? $session->initial_difficulty;

        // 根据用户表现调整难度
        if ($sentiment['score'] > 80) {
            $currentDifficulty = min(5, $currentDifficulty + 1);
        } elseif ($sentiment['score'] < 40) {
            $currentDifficulty = max(1, $currentDifficulty - 1);
        }

        $session->update(['final_difficulty' => $currentDifficulty]);

        return $currentDifficulty;
    }

    /**
     * 获取对话历史
     */
    private function getConversationHistory($session)
    {
        return $session->messages()
                      ->orderBy('created_at')
                      ->get(['sender_type', 'message'])
                      ->toArray();
    }

    /**
     * 计算AI情绪
     */
    private function calculateAIEmotion($userEmotionScore, $difficulty)
    {
        // 基础情绪受用户情绪影响
        $baseEmotion = $userEmotionScore;
        
        // 难度越高，AI越难取悦
        $difficultyModifier = (6 - $difficulty) * 5;
        
        return max(0, min(100, $baseEmotion + $difficultyModifier - 25));
    }

    /**
     * 检查会话完成条件
     */
    private function checkSessionCompletion($session)
    {
        $messageCount = $session->messages()->count();
        
        // 如果消息数量达到20条，自动结束会话
        if ($messageCount >= 20) {
            $finalEmotionScore = $this->calculateFinalEmotionScore($session);
            $successAchieved = $finalEmotionScore >= 70;

            $session->update([
                'status' => $successAchieved ? 'completed' : 'failed',
                'completed_at' => now(),
                'final_emotion_score' => $finalEmotionScore,
                'success_achieved' => $successAchieved
            ]);
        }
    }

    /**
     * 计算最终情绪分数
     */
    private function calculateFinalEmotionScore($session)
    {
        $aiMessages = $session->messages()
                             ->where('sender_type', 'ai')
                             ->whereNotNull('emotion_score')
                             ->get();

        if ($aiMessages->isEmpty()) {
            return 50;
        }

        // 计算加权平均，后面的消息权重更高
        $totalScore = 0;
        $totalWeight = 0;
        
        foreach ($aiMessages as $index => $message) {
            $weight = $index + 1; // 权重递增
            $totalScore += $message->emotion_score * $weight;
            $totalWeight += $weight;
        }

        return round($totalScore / $totalWeight);
    }
}